const { getArtArtistById } = require("../../../utils/request");
const config = require("../../../utils/config");

Page({
    data: {
        artists: {}, // 艺术家信息
        artworks: [], // 艺术作品数据
        pageNum: 1, // 当前页数
        pageSize: 6, // 每页显示的条数
        isBiographyExpanded: false, // 传记是否展开
    },

    onLoad: function (options) {
        const id = options.id; // 从页面参数中获取艺术家ID
        // const id = 1;
        this.loadArtistDetail(id); // 加载艺术家详细信息
    },

    // 加载艺术家详细信息
    loadArtistDetail: function (id) {
        const { pageNum, pageSize } = this.data;
        getArtArtistById({ id, pageNum, pageSize }).then(res => {
            if (res.code === '00000') {
                // 在artists的photoUrl前加上config.ImageURL
                const artists = {
                    ...res.data,
                    photoUrl: config.ImageURL + res.data.photoUrl
                };

                // 在artists的图片URL前加上config.ImageURL
                const artworks = (res.data.artworks || []).map(item => ({
                    ...item,
                    primaryImageSmallUrl: config.ImageURL + item.primaryImageSmallUrl
                }));

                // 处理biography，将<p>替换为<view class="paragraph">
                if (artists.biography) {
                  artists.biography = this.replacePTags(artists.biography);
                }

                this.setData({
                    artists,
                    artworks
                });
            } else {
                wx.showToast({
                    title: '加载失败，请重试',
                    icon: 'none'
                });
            }
        }).catch(err => {
            wx.showToast({
                title: '网络错误，请重试',
                icon: 'none'
            });
        });
    },

    // 将<p>标签替换为<div class="paragraph">
    replacePTags: function (html) {
      return html
          .replace(/<p>/g, '<div class="paragraph">') // 替换<p>为<view class="paragraph">
          .replace(/<\/p>/g, '</div>'); // 替换</p>为</view>
    },

    // 切换传记展开/收起状态
    toggleBiography: function () {
        this.setData({
            isBiographyExpanded: !this.data.isBiographyExpanded,
        });
    },

    // 切换传记展开/收起状态
    toggleBiography() {
        this.setData({
          isBiographyExpanded: !this.data.isBiographyExpanded
        });
    },

    // 查看全部作品
    viewAllArtworks: function () {
        wx.navigateTo({
            url: `/pages/artist/artwork-list/artwork-list?artistId=${this.data.artists.id}&artistName=${this.data.artists.artistName}`,
        });
    },

    // 点击作品跳转到作品详情
    onArtworkTap: function (e) {
        const artworkId = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/pages/artwork/detail/detail?artWorkId=${artworkId}`,
        });
    },
});